package com.mew.chess.core.common.handler;

import com.github.benmanes.caffeine.cache.RemovalCause;
import com.mew.common.dc.redis.AucRedisService;
import com.mew.common.rest.bo.GameSession;
import com.mew.common.rest.bo.MewSession;
import com.zebra.common.ExpiredExitMessage;
import com.zebra.common.OnlineType;
import com.zebra.common.ZebraException;
import com.zebra.remoting.config.BasisCommandCode;
import com.zebra.remoting.tms.TmsSendMessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
@Slf4j
public class ExpireCacheServer {

    @Autowired
    private AucRedisService aucRedisService;

    public void doRemovalListener(@Nullable Long key, @Nullable GameSession value, @NonNull RemovalCause cause){
        if (cause.equals(RemovalCause.EXPIRED)){
            try {
                ChessSessionManager.decrementNumber.getAndDecrement();
                MewSession session = aucRedisService.getSession(key);
                log.info("Cache GameSession EXPIRED : vtk:{}; vroomId {};  {}", value.getTk(), value.getRoomId(),   null == session ? "session is null" : session.toString());
                value.setWeakClose(true);

                if (null == session){
                    ChessEEHandler chessEEHandler = InitializeEEHandlerMapping.getMapping(value.getVfx());
                    chessEEHandler.expiredExit(value.getUserId(), value.getGameId(), value.getRoomId());
                    return;
                }

                if (session.rid == value.getRoomId() && session.tk == value.getTk()){
                    ChessEEHandler chessEEHandler = InitializeEEHandlerMapping.getMapping(value.getVfx());
                    chessEEHandler.expiredExit(value.getUserId(), value.getGameId(), value.getRoomId());
                    if (OnlineType.Online.value() == session.onl && value.channelFine()){
                        TmsSendMessageUtil.pushMessage(value.getChannel(),  BasisCommandCode.EXPIRED.cmd(), value.getUserId(), value.getTk(), new ExpiredExitMessage(1, value.getGoldNumber()));
                    }
                }
            } catch (ZebraException e) {
                log.error("Cache GameSession EXPIRED : userId: {} {}", key, e.getMessage());
            }
        }
    }

}
